package com.sx.pipeline.ui.chat

import android.content.Intent
import android.net.Uri
import android.view.View
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.tabs.TabLayoutMediator
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.AttachPopupView
import com.lxj.xpopup.enums.PopupPosition
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.app.base.CYDataBindingBaseFragment
import com.sx.pipeline.app.config.IntentKey
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.FragChatBinding
import com.sx.pipeline.repos.http.res.ContactUserVo
import com.sx.pipeline.repos.http.res.RongGroupVO
import com.sx.pipeline.repos.http.res.UserInfoVO
import com.sx.pipeline.ui.chat.detail.ConversationActivity
import io.rong.imkit.RongIM
import io.rong.imkit.userinfo.RongUserInfoManager
import io.rong.imkit.userinfo.UserDataProvider
import io.rong.imkit.userinfo.model.GroupUserInfo
import io.rong.imkit.utils.RouteUtils
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation


/**
 * @Author: YY
 * @Date: 2022/4/7
 * @Description: 聊天
 */
class ChatFragment : CYDataBindingBaseFragment<FragChatBinding, ChatVM>(R.layout.frag_chat),
    View.OnClickListener {

    private lateinit var chatTypePageAdapter: ChatPageAdapter

    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
        initPager()
    }

    override fun onResume() {
        super.onResume()
        mViewModel.getRongAllContact()
        mViewModel.getRongGroupList()
        mViewModel.updateUserInfo()
//        setGroupMemberInfo()
    }

    override fun initViewObservable() {
        observe(mViewModel.userInfoDataEvent) {
            //初始化融云
            it?.let { it1 -> initRongIM(it1) }
        }
        observe(mViewModel.allRongContactListEvent) {
            if (it != null && it.size != 0) {
                refreshRongUserInfo(it)
            }
        }
        observe(mViewModel.groupListEvent) {
            if (it != null) {
                refreshRongGroupInfo(it)
            }
        }

        observe(mViewModel.imId){
            RouteUtils.routeToConversationActivity(
                context,
                Conversation.ConversationType.PRIVATE,
                it.toString()
            );
        }

    }

    /**
     * 初始化ViewPager
     */
    private fun initPager() {
        if (mBinding.viewPager.adapter == null) {
            chatTypePageAdapter = ChatPageAdapter(
                mViewModel.getChatTabsList(), childFragmentManager, lifecycle
            )
        }
        mBinding.viewPager.adapter = chatTypePageAdapter

        //绑定tabLayout和viewPager
        TabLayoutMediator(
            mBinding.tab, mBinding.viewPager,
            true, true
        ) { tab, position ->
            tab.text = mViewModel.getChatTabsList()[position]
        }.attach()
    }

    override fun initListener() {
        super.initListener()
        mBinding.ivChatAdd.setOnClickListener {
            val attachPopupView: AttachPopupView = XPopup.Builder(context)
                .hasShadowBg(false) //                        .isViewMode(true)
                .isClickThrough(true) //                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                //                        .isDarkTheme(true)
                //                        .popupAnimation(PopupAnimation.ScrollAlphaFromTop) //NoAnimation表示禁用动画
                //                        .isCenterHorizontal(true) //是否与目标水平居中对齐
//                                        .offsetY(60)
                .offsetX(50)
                .popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .atView(mBinding.ivChatAdd) // 依附于所点击的View，内部会自动判断在上方或者下方显示
                .asAttachList(
                    arrayOf(
                        getString(R.string.txt_peer_to_peer_communication),
                        getString(R.string.txt_start_group_chat)
                    ),
                    intArrayOf(),
                    { position, text ->
                        run {
                            when (position) {
                                0 -> ARouter.getInstance().build(RoutePath.Chat.CHAT_SEARCH)
                                    .withInt(IntentKey.TYPE, 0).navigation()
                                1 -> ARouter.getInstance().build(RoutePath.Chat.CHAT_SEARCH)
                                    .withInt(IntentKey.TYPE, 1).navigation()
                            }
                        }
                    },
                    0,
                    0 /*, Gravity.LEFT*/
                )

            attachPopupView.show()
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            //组织架构
            R.id.tv_search -> ARouter.getInstance().build(RoutePath.Chat.CHAT_SEARCH)
                .withInt(IntentKey.TYPE, 0).navigation()
            R.id.btn_service -> {
//                val uri: Uri = Uri.parse("https://web.jiaxincloud.com/onekey.html?id=yzbtyxnuyjvsdg&appName=gxt365&appChannel=20001")
//                val intent = Intent(Intent.ACTION_VIEW, uri)
//                startActivity(intent)
//                ARouter.getInstance().build(RoutePath.Setting.CONTACT_SERVICE).navigation()
                mViewModel.intentService()
            }
        }
    }

    private fun initRongIM(result: UserInfoVO) {
        Logs.d("token......"+result.ryToken)
        Logs.d("re融云状态......"+RongIM.getInstance().currentConnectionStatus.message)
        //连接融云
        RongIM.connect(result.ryToken,
            object : RongIMClient.ConnectCallback() {
                override fun onSuccess(userId: String) {
                    Logs.d("re融云连接成功")
                    // 登录成功，跳转到默认会话列表页。
                    RouteUtils.registerActivity(
                        RouteUtils.RongActivityType.ConversationActivity,
                        ConversationActivity::class.java
                    )
                }

                override fun onError(connectionErrorCode: RongIMClient.ConnectionErrorCode) {
                    Logs.d("re融云连接失败$connectionErrorCode")
                }

                override fun onDatabaseOpened(databaseOpenStatus: RongIMClient.DatabaseOpenStatus) {}
            })


    }

    private fun refreshRongUserInfo(friendList: List<ContactUserVo>) {
        //融云IM -> 用户信息提供者
        //加载自己的用户信息
        RongIM.getInstance().refreshUserInfoCache(
            io.rong.imlib.model.UserInfo(
                mViewModel.mModel.getUserData()?.userUnitId,
                mViewModel.mModel.getUserData()?.userName,
                Uri.parse(mViewModel.mModel.getUserData()?.avatar)
            )
        )
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val userInfo = io.rong.imlib.model.UserInfo(
                friendList[i].userUnitId.toString(),
                friendList[i].userName,
                Uri.parse(friendList[i].avatar)
            )
            //通过网络请求动态加载用户信息
            RongIM.getInstance().refreshUserInfoCache(userInfo)
            Logs.d("re缓存用户信息成功：" + userInfo)
        }
    }

    private fun refreshRongGroupInfo(friendList: List<RongGroupVO>) {
        //融云IM -> 刷新群组信息
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val group = io.rong.imlib.model.Group(
                friendList[i].id,
                friendList[i].name,
                Uri.parse("")
            )
            //通过网络请求动态加载群信息
            RongIM.getInstance().refreshGroupInfoCache(group)
            Logs.d("re缓存群聊信息成功：" + group)
        }
    }

    private fun setGroupMemberInfo(){
        RongIM.getInstance().setGroupMembersProvider { groupId, callback ->
            Logs.d("rongim"+groupId)

        }

        RongUserInfoManager.getInstance().setGroupUserInfoProvider({ groupId, userId ->
            val groupUserInfo = GroupUserInfo(
                groupId, userId,
                "小花$userId"
            )

            Logs.d("rongim"+groupId)
            groupUserInfo
        },true)
    }
}